package cn.area.act.my;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.RelativeLayout.LayoutParams;
import cn.area.R;
import cn.area.adapter.JourneyItemizedOverlay;
import cn.area.app.BMapApiDemoApp;
import cn.area.domain.TripInfo;
import cn.area.global.Config;
import cn.area.global.MapConfig;
import cn.area.view.MyMapView;
import cn.baidumap.util.CommonsUtil;
import cn.baidumap.util.DeviceTools;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;

public class JourneyRecordsActivity extends MapActivity implements
		OnTouchListener {
	MyMapView mapView;
	LocationListener mLocationListener = null;// onResume时注册此listener，onPause时需要Remove
	MyLocationOverlay mLocationOverlay = null; // 定位图层
	MapController mapController;
	BMapApiDemoApp app;
	List<Overlay> overlays;
	JourneyItemizedOverlay overlay;
	GeoPoint point;
	double lat, lng;
	GeoPoint thepoint = null;
	Projection projection;
	private Handler handler;
	
	boolean nowflag = true;

	// **********新方法缩放地图***********//
	double min_x, min_y, max_x, max_y;
	private Bitmap bmpMark;// 标记(移动的图片)
	
	int playTimes = 0;//播放时当前移动的次数
	
	
	private GeoPoint centerPoint;
	private boolean start = true;
	private int currentIndex = 0;
	private long durationTime;
	
	private int blocks = 150;//把一条线分成多少段，这个段数其实应该根据线的长短定一个比例来算出来，暂时定义为150


	// 播发动作
	private static final int PLAY_START = 0;// 播放开始
	private static final int PLAY_MOVE = 1;// 移动
	private static final int PLAY_SCALE = 2;// 缩放
	private static final int PLAY_TO_CENTER = 3;
	private static final int PLAY_ALERT_POP = 4;
	private static final int PLAY_STOP = 5;
	private static final String TAG = "JourneyRecordsActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.journeyrecords);

		findViews();
		initRes();
		setVavles();
		setListener();

		getHandler();

	}

	private void setVavles() {
		MapConfig.bitmapPeople = bmpMark;
		// 初始化地图
		setMapApp();
	}

	private void initRes() {

		// 初始移动的图标(头像)
		bmpMark = BitmapFactory.decodeResource(getResources(),
				R.drawable.usericon);

		// 初始化popupView
		LayoutInflater inflater = LayoutInflater.from(this);
		MapConfig.popupView = inflater.inflate(R.layout.popview, null);
		MapConfig.popupView.setVisibility(View.GONE);
		
		// 初始化popupViewPeople
		View view = inflater.inflate(R.layout.overlaypop_people, null);
		MapConfig.popPeopleView = view;
		MapConfig.popPeopleView.setVisibility(View.GONE);
		
		// 初始化popupViewPeople
		MapConfig.moveView = inflater.inflate(R.layout.move_view, null);
		MapConfig.moveView.setVisibility(View.GONE);

		// 得到屏幕大小
		Config.deviceWidthHeight = DeviceTools.getDeviceInfo(this);
		Config.deviceWidth = Config.deviceWidthHeight[0];
		Config.deviceHeight = Config.deviceWidthHeight[1];

	}

	private void findViews() {
		mapView = (MyMapView) findViewById(R.id.journeyrecordsmapview);
	}

	// 地图监听事件
	private void setListener() {

		mapView.setOnTouchListener(this);

		mLocationListener = new LocationListener() {
			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					point = new GeoPoint((int) (22.795200 * 1e6),
							(int) (108.367837 * 1e6));
					lat = location.getLatitude();
					lng = location.getLongitude();
					// mapView.getController().animateTo(point);
					if (nowflag == true) {
						setPostion();
						nowflag = false;
					}

				}
			}

		};
		
	}

	// 地图动画效果 延时执行
	private void getHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				
				if(msg.what != PLAY_START){
					//移动前先把图片关闭
					MapConfig.popupView.setVisibility(View.GONE);
					MapConfig.popPeopleView.setVisibility(View.GONE);
				}
				switch (msg.what) {
				// 开始
				case PLAY_START:// 第一个点
					// 显示第一个点的图片文字popView
					mapView.getController().animateTo(thepoint);
					popPopView(thepoint);
					mapController.setZoom(10);
					break;
				case PLAY_TO_CENTER:
					mapView.getController().animateTo(centerPoint);
					break;
				case PLAY_SCALE:
					// 缩放地图能看到两个点为止
					scalePointToSee(MapConfig.pointList.get(currentIndex - 1),
							MapConfig.pointList.get(currentIndex));
					break;
				case PLAY_MOVE:
					// 动画从这走到那
					double p1Lat = MapConfig.infos.get(currentIndex-1).getLat();
					double p2Lat = MapConfig.infos.get(currentIndex).getLat();
					double p1Lng = MapConfig.infos.get(currentIndex-1).getLng();
					double p2Lng = MapConfig.infos.get(currentIndex).getLng();
					double latRate = (p1Lat - p2Lat)/blocks;
					double lngRate = (p1Lng - p2Lng)/blocks;
					GeoPoint gp = new GeoPoint((int)((p1Lat-latRate*playTimes)* 1e6), (int)((p1Lng - lngRate*playTimes)* 1e6));
					
					//Log.i(TAG, "Lat:"+gp.getLatitudeE6());
					//Log.i(TAG, "Lng:"+gp.getLongitudeE6());
					//Log.i(TAG, "playTimes:"+playTimes);
					
					mapView.updateViewLayout(MapConfig.moveView,new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT, gp,
							MapView.LayoutParams.CENTER));
					MapConfig.moveView.setVisibility(View.VISIBLE);

					break;
				case PLAY_ALERT_POP:
					// 定位中心位置 显示popwindow
					MapConfig.moveView.setVisibility(View.GONE);
					mapView.getController().animateTo(thepoint);
					
					popPopView(thepoint);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					mapView.getController().setZoom(9);
					break;
				case PLAY_STOP:
					
					break;
				}
			}
		};
	}
	
	// 播放
	public void paly(View view) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					int i = currentIndex;
					for (; i < MapConfig.infos.size(); i++) {
						// 1.点击播放的第一个点，定位到当前点击的点（或用户没有点击，从第一个点开始）
						if (start) {
							currentIndex = i;
							// 当前点
							thepoint = new GeoPoint((int) (MapConfig.infos.get(
									i).getLat() * 1e6), (int) (MapConfig.infos
									.get(i).getLng() * 1e6));
							handler.sendEmptyMessage(PLAY_START);
							// 暂停一下，等待定位到当前点击的点，显示popView
							Thread.sleep(3000);
							start = false;
						} else {
							// 开始移动 向前走一个点
							currentIndex = i;

							// 当前点
							thepoint = new GeoPoint((int) (MapConfig.infos.get(
									currentIndex).getLat() * 1e6),
									(int) (MapConfig.infos.get(currentIndex)
											.getLng() * 1e6));

							// 2.确定中点
							centerPoint = new GeoPoint(
									(int) ((MapConfig.infos.get(currentIndex)
											.getLat() * 1e6 + MapConfig.infos
											.get(currentIndex - 1).getLat() * 1e6)) / 2,
									(int) ((MapConfig.infos.get(currentIndex)
											.getLng() * 1e6 + MapConfig.infos
											.get(currentIndex - 1).getLng() * 1e6)) / 2);
							handler.sendEmptyMessage(PLAY_TO_CENTER);
							Thread.sleep(400);
							// 3.计算距离,将两点都缩放到屏幕中间
							handler.sendEmptyMessage(PLAY_SCALE);
							Thread.sleep(1000);
							// 4.移动标记
							// 设置移动动画时间
							double distance = CommonsUtil
									.getDistanceOfTwoPoint(MapConfig.pointList
											.get(currentIndex - 1),
											MapConfig.pointList
											.get(currentIndex));
							durationTime = (long) (8000 / 800 * distance);// 按8秒移动800的距离当移动速率
							for(int j=0;j<=blocks;j++){//j<=50是指当前我把这条线分成了50个点
								playTimes = j;
								handler.sendEmptyMessage(PLAY_MOVE);
								Thread.sleep(durationTime/blocks);
							}
							// 5.显示pop
							handler.sendEmptyMessage(PLAY_ALERT_POP);
							Thread.sleep(2000);
						}
						
						if (currentIndex == MapConfig.pointList.size() - 1) {
							//play完后，又将第一个点确认为播放的开始位置
							currentIndex = 0;
							start = true;
						}
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}).start();
	}
	

	/**
	 * 缩放至可以见到二个点
	 * @param p1
	 * @param p2
	 */
	protected void scalePointToSee(Point p1, Point p2) {
		min_x = Math.min(p1.x, p2.x);
		max_x = Math.max(p1.x, p2.x);
		min_y = Math.min(p1.y, p2.y);
		max_y = Math.max(p1.y, p2.y);
		if (min_x > 0 && max_x < Config.deviceWidth && min_y > 0
				&& max_y < Config.deviceHeight) {
		} else {
			System.out.println(min_x);
			mapController.setZoom(mapView.getZoomLevel() - 1);
			mapView.invalidate();
			// 重复缩放直到OK
			handler.sendEmptyMessage(PLAY_SCALE);
		}

	}

	// 初始化地图
	private void setMapApp() {
		// TODO Auto-generated method stub
		app = (BMapApiDemoApp) this.getApplication();
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey,
					new BMapApiDemoApp.MyGeneralListener());
		}
		app.mBMapMan.start();
		// 如果使用地图SDK，请初始化地图Activity
		super.initMapActivity(app.mBMapMan);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(mLocationOverlay);
		mapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mapView.setDrawOverlayWhenZooming(true);
		mLocationOverlay.enableMyLocation();// 启用定位
		mapView.getOverlays().add(mLocationOverlay);
		// 设置启用内置的缩放控件
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		mapController.setZoom(15);
		projection = mapView.getProjection();

	}

	// 地图上添加位置图层
	private void setPostion() {
		// TODO Auto-generated method stub
		mapView.getOverlays().clear();
		mLocationOverlay = new MyLocationOverlay(this, mapView);
		mLocationOverlay.enableMyLocation();// 启用定位
		mapView.getOverlays().add(mLocationOverlay);
		getTripLines();

	}

	/**
	 * 初始化点并标记
	 */
	private void getTripLines() {
		MapConfig.infos = new ArrayList<TripInfo>();
		TripInfo info = null;
		List<String> textStrings = null;
		List<String> imageStrings = null;
		info = new TripInfo();
		textStrings = new ArrayList<String>();
		textStrings.add("我来了111");
		info.setDescriptionsList(textStrings);
		imageStrings = new ArrayList<String>();
		imageStrings.add("图片1111");
		info.setDescriptionsList(textStrings);
		info.setDescriptionsList(imageStrings);
		info.setLat(39.94236006);
		info.setLng(116.3134392);
		info.setOrder(1);
		MapConfig.infos.add(info);
		
		
		/*
		//在1跟2之间再画10个点
		double bili1 = Math.abs(39.94236006 - 22.790073)/10;
		double bili2 = Math.abs(116.3134392 - 108.390375)/10;
		
		for(int i=1;i<=10;i++){
			info = new TripInfo();
			textStrings = new ArrayList<String>();
			textStrings.add("我来了");
			info.setDescriptionsList(textStrings);
			imageStrings = new ArrayList<String>();
			imageStrings.add("图片");
			info.setDescriptionsList(textStrings);
			info.setDescriptionsList(imageStrings);
			info.setLat(39.94236006 - bili1*i);
			info.setLng(116.3134392 - bili2*i);
			info.setOrder(i+3);
			MapConfig.infos.add(info);
		}
		*/
		
		
		info = new TripInfo();
		textStrings = new ArrayList<String>();
		textStrings.add("我来了2222");
		info.setDescriptionsList(textStrings);
		imageStrings = new ArrayList<String>();
		imageStrings.add("图片22222");
		info.setDescriptionsList(textStrings);
		info.setDescriptionsList(imageStrings);
		info.setLat(22.790073);
		info.setLng(108.390375);
		info.setOrder(2);
		MapConfig.infos.add(info);

		info = new TripInfo();
		textStrings = new ArrayList<String>();
		textStrings.add("我来了3333");
		info.setDescriptionsList(textStrings);
		imageStrings = new ArrayList<String>();
		imageStrings.add("图片33333");
		info.setDescriptionsList(textStrings);
		info.setDescriptionsList(imageStrings);
		info.setLat(26.795582);
		info.setLng(90.365438);
		info.setOrder(3);
		MapConfig.infos.add(info);
		
		
		
		
		

		// 标记点
		for (TripInfo tripInfo : MapConfig.infos) {
			overlay = new JourneyItemizedOverlay(getResources().getDrawable(
					R.drawable.positionc), this);
			overlays = mapView.getOverlays();
			GeoPoint point = new GeoPoint((int) (tripInfo.getLat() * 1e6),
					(int) (tripInfo.getLng() * 1e6));
			OverlayItem overlayitem = new OverlayItem(point, tripInfo
					.getDescriptionsList().get(0), tripInfo
					.getDescriptionsList().get(0));
			overlay.addOverlay(overlayitem);
			overlays.add(overlay);
			mapView.getController().zoomToSpan((int) (tripInfo.getLat() * 1e6),
					(int) (tripInfo.getLng() * 1e6));
		}

		// 添加pop
		mapView.addView(MapConfig.popupView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));
		
		// 添加popPeopleView
		mapView.addView(MapConfig.popPeopleView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));
		
		// 添加moveView
		mapView.addView(MapConfig.moveView, new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
				MapView.LayoutParams.TOP_LEFT));

		mapView.getController().setZoom(mapView.getZoomLevel() + 1);

	}

	
	/**
	 * 弹出气泡
	 * @param i
	 */
	public void popPopView(GeoPoint point) {
		mapView.updateViewLayout(MapConfig.popupView,
				new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, point,
						MapView.LayoutParams.BOTTOM_CENTER));
		mapView.updateViewLayout(MapConfig.popPeopleView,
				new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, point,
						MapView.LayoutParams.BOTTOM_CENTER));
		
		MapConfig.popupView.setVisibility(View.VISIBLE);
		MapConfig.popPeopleView.setVisibility(View.VISIBLE);
	}


	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onPause() {
		BMapApiDemoApp app = (BMapApiDemoApp) this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mLocationOverlay.disableMyLocation();
		mLocationOverlay.disableCompass(); // 关闭指南针
		app.mBMapMan.stop();
		MapConfig.popupView.setVisibility(View.GONE);
		if (overlays != null) {
			overlays.remove(overlay);
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		BMapApiDemoApp app = (BMapApiDemoApp) this.getApplication();
		// 注册定位事件，定位后将地图移动到定位点
		app.mBMapMan.getLocationManager().requestLocationUpdates(
				mLocationListener);
		mLocationOverlay.enableMyLocation();
		mLocationOverlay.enableCompass(); // 打开指南针
		app.mBMapMan.start();
		if (overlays != null) {
			overlays.remove(overlay);
		}
		super.onResume();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	
	
	
	
	
	
	
}
